package com.tan.androidtest.process;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.TextView;

import com.tan.androidtest.ITestAidlInterface;
import com.tan.androidtest.ITestAidlInterfaceCallback;
import com.tan.androidtest.R;
import com.tan.androidtest.base.BaseActivity;
import com.tan.androidtest.service.TestMyAIDLService;

/**
 * 测试Activity和service的通讯
 * 使用ServiceConnection Binder
 */
public class TestActivityConnectServiceActivity extends BaseActivity {

    private TextView mTvTest;
    private ITestAidlInterface mITestAidlInterface;
    private MyITestAidlInterfaceCallback callback;

    @Override
    public int initLayoutId() {
        return R.layout.activity_test_activity_connect_service_layout;
    }

    @Override
    public void initTitle(TextView tv_bar_left, TextView tv_bar_title, TextView tv_bar_right) {
        tv_bar_title.setText("测试Activity和service的通讯");
    }

    @Override
    public void initView() {
        mTvTest = findViewById(R.id.tv_test);
    }

    @Override
    public void initData() {
        Intent intent = new Intent(getApplicationContext(), TestMyAIDLService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                mITestAidlInterface = ITestAidlInterface.Stub.asInterface(service);
                callback = new MyITestAidlInterfaceCallback();
                mITestAidlInterface.registerCallback(callback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            try {
                mITestAidlInterface.unRegisterCallback(callback);
                mITestAidlInterface = null;
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connection != null) {
            unbindService(connection);
        }
    }

    class MyITestAidlInterfaceCallback extends ITestAidlInterfaceCallback.Stub {

        @Override
        public void onCallback(final int process) throws RemoteException {
            getWindow().getDecorView().post(new Runnable() {
                @Override
                public void run() {
                    Log.i("==--", "回调来了");
                    mTvTest.setText("" + process);
                }
            });
        }
    }
}
